package cn.hs.ph.servlet;

import cn.hs.ph.dao.impl.GoodsDaoImpl;
import cn.hs.ph.entity.Goods;
import cn.hs.ph.entity.Station;
import cn.hs.ph.util.Result;
import com.alibaba.fastjson.JSON;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet("/goods")
public class GoodsServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Map<String, String> map = new HashMap<>();
        GoodsDaoImpl goodsDao = new GoodsDaoImpl();
        String action = req.getParameter("action");
        if (action.equals("select")) {
            String pageNum = req.getParameter("pageNum");
            String pageSize = req.getParameter("pageSize");
            String startTime = req.getParameter("startTime");
            String endTime = req.getParameter("endTime");
            String goodsName = req.getParameter("goodsName");
            String shopName = req.getParameter("shopName");
            String goodsStatus = req.getParameter("goodsStatus");
            map.put("pageNum", pageNum);
            map.put("pageSize", pageSize);
            map.put("startTime", startTime);
            map.put("endTime", endTime);
            map.put("goodsName", goodsName);
            map.put("shopName", shopName);
            map.put("goodsStatus", goodsStatus);
            List<Goods> list = goodsDao.selectAll(map);
            int total = goodsDao.selectCount(map);
            Map<Object, Object> map1 = new HashMap<>();
            map1.put("list", list);
            map1.put("total", total);
//            Result result = Result.success("查询成功");
//            map1.put("status",JSON.toJSONString(map1));
            Result result = Result.success(map1);
            resp.getWriter().write(JSON.toJSONString(result));
        }
        else if("update".equals(action)){
            int goodsStatus = Integer.parseInt(req.getParameter("goodsStatus"));
            int goodsId = Integer.parseInt(req.getParameter("goodsId"));
            int update = goodsDao.update(goodsStatus,goodsId);
            if(update != 0){
                Result<Station> result = Result.success("成功");
                resp.getWriter().write(JSON.toJSONString(result));
            }else {
                Result<Station> result = Result.error("失败");
                resp.getWriter().write(JSON.toJSONString(result));
            }
        }
    }
}
